package com.kaiwukj.android.ufamily.mvp.ui.page.home.mine;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.app.constant.ExtraCons;
import com.kaiwukj.android.ufamily.mvp.helper.AccountStore;
import com.kaiwukj.android.ufamily.mvp.http.api.service.CommunityService;
import com.kaiwukj.android.ufamily.mvp.http.callback.ApiCallBack;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.DynamicAttentionEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.GlobalEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.HomeEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.UpdateUserInfoEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.CommunityResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.UserResult;
import com.kaiwukj.android.ufamily.mvp.http.utils.RxUtils;
import com.kaiwukj.android.ufamily.mvp.ui.page.mine.settings.SettingFragment;
import com.kaiwukj.android.ufamily.mvp.ui.widget.GridSpaceItemDecoration;
import com.kaiwukj.android.ufamily.utils.ServiceHistoryStore;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

import static com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt.MineInfoUrl;

public class MineFragment extends BaseFragment {

    private static final int PICK_COMMUNITY = 101;

    /*@BindView(R.id.toolbar)
    Toolbar toolbar;*/
    //@BindView(R.id.scroll_container)
    // ScrollContainer scrollContainer;
    /*@BindView(R.id.container_title)
    ViewGroup containerTitle;*/
    //@BindView(R.id.toolbar)
    //Toolbar toolbar;
    @BindView(R.id.tv_community)
    TextView tvCommunity;
    //  @BindView(R.id.refresh_layout)
    //  SmartRefreshLayout refreshLayout;
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.iv_user_vip_flag)
    ImageView ivUserVipFlag;
    @BindView(R.id.tv_user_desc)
    TextView tvUserDesc;
    @BindView(R.id.tv_like_num)
    TextView tvLikeNum;
    @BindView(R.id.tv_fans_num)
    TextView tvFansNum;
    @BindView(R.id.tv_attention_num)
    TextView tvAttentionNum;

    @BindView(R.id.rv_vip_item)
    RecyclerView rvVipItem;

    @BindView(R.id.rv_property)
    RecyclerView rvProperty;//房屋，车辆等财产
    @BindView(R.id.rv_service)
    RecyclerView rvService;
    @BindView(R.id.rv_sys)
    RecyclerView rvSys;

    @BindView(R.id.tv_invalid_date)
    TextView tvInvalidDate;
    @BindView(R.id.tv_vip_action)
    TextView tvVipAction;

    private PersonVipServiceAdapter mVipServiceAdapter;

    private ServiceAdapter mPropertyAdapter;
    private ServiceAdapter mServiceAdapter;
    private ServiceAdapter mSysAdapter;

    @OnClick(R.id.container_person)
    void intent2PersonIndex() {
        ARouter.getInstance().build(ARouterUrlKt.DynamicPersonUrl)
                .navigation();
    }

    @OnClick(R.id.iv_avatar)
    void intent2PersonInfo() {
        ARouter.getInstance().build(ARouterUrlKt.PersonInfoUpdateUrl)
                .navigation();
    }

    @OnClick(R.id.container_community)
    void pickCommunity() {
        ARouter.getInstance().build(ARouterUrlKt.CommunityUpdateUrl)
                .withInt("pickAction", 1)
                .navigation(getActivity(), PICK_COMMUNITY);
    }

   @OnClick(R.id.toolbar)
    void pickToolbarCommunity(View view){
       ARouter.getInstance().build(ARouterUrlKt.CommunityUpdateUrl)
               .withInt("pickAction", 1)
               .navigation(getActivity(), PICK_COMMUNITY);
    }

    @OnClick({R.id.container_attention, R.id.container_fans})
    void onFansClick(View view) {
        UserResult userResult = getApp().getUserInfo();
        if (userResult == null) return;
        if (view.getId() == R.id.container_attention) {
            ARouter.getInstance().build(ARouterUrlKt.PersonFansUrl)
                    .withInt("type", 0)
                    .navigation();
        } else {
            ARouter.getInstance().build(ARouterUrlKt.PersonFansUrl)
                    .withInt("type", 1)
                    .navigation();
        }
    }

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
    }

    @Override
    protected void initView() {
        //  refreshLayout.setEnableLoadMore(false);
        //  refreshLayout.setOnRefreshListener(refreshLayout -> EventBus.getDefault().post(new UpdateUserInfoEvent(UpdateUserInfoEvent.REQUEST)));

        rvVipItem.addItemDecoration(new GridSpaceItemDecoration(0, 10));
        mVipServiceAdapter = new PersonVipServiceAdapter();
        rvVipItem.setNestedScrollingEnabled(false);
        rvVipItem.setAdapter(mVipServiceAdapter);
        mVipServiceAdapter.setList(getVipServiceItem());

        //scrollContainer.setTitleBarView(containerTitle);
        rvProperty.setLayoutManager(new GridLayoutManager(getContext(), 4));
        rvProperty.setNestedScrollingEnabled(false);
        //rvProperty.addItemDecoration(new GridSpacingItemDecoration(4, SizeUtils.dp2px(8), false));
        mPropertyAdapter = new ServiceAdapter();
        rvProperty.setAdapter(mPropertyAdapter);


        rvService.setLayoutManager(new GridLayoutManager(getContext(), 4));
        rvService.setNestedScrollingEnabled(false);
        mServiceAdapter = new ServiceAdapter();
        mServiceAdapter.setOnItemClickListener(onItemClickListener);
        rvService.setAdapter(mServiceAdapter);

        rvSys.setLayoutManager(new GridLayoutManager(getContext(), 4));
        rvSys.setNestedScrollingEnabled(false);
        mSysAdapter = new ServiceAdapter();
        rvSys.setAdapter(mSysAdapter);
        mSysAdapter.setOnItemClickListener(onItemClickListener);

        mPropertyAdapter.setOnItemClickListener(onItemClickListener);

        tvVipAction.setOnClickListener(v -> {
            ARouter.getInstance().build(ARouterUrlKt.MyVipService)
                    .navigation();
        });
    }

    private OnItemClickListener onItemClickListener = (adapter, view, position) -> {
        switch (((ServiceAdapter) adapter).getServiceType(position)) {
            case ServiceBean.HOUSE:
                ARouter.getInstance().build(ARouterUrlKt.MyHouseUrl).navigation();
                break;
            case ServiceBean.HOUSE_ORDER:
                ARouter.getInstance().build(ARouterUrlKt.PayFeeUrl)
                        .navigation();
                break;
            case ServiceBean.QUAN:
                showMessage("暂无优惠券");
                break;
            case ServiceBean.COMMITTEE:
                showMessage("暂未成立");
                break;
            case ServiceBean.ORDER:
                ARouter.getInstance().build(ARouterUrlKt.OrderListUrl)
                        .navigation();
                break;
            case ServiceBean.EVALUATE:
                ARouter.getInstance().build(ARouterUrlKt.OrderEvaluateUrl).navigation();
                break;
            case ServiceBean.ACTIVE:
                ARouter.getInstance().build(ARouterUrlKt.MyActiveUrl).navigation();
                break;
            case ServiceBean.CIRCLE:
                ARouter.getInstance().build(ARouterUrlKt.DynamicPersonUrl)
                        .navigation();
                break;
            case ServiceBean.PERSON_INFO:
                ARouter.getInstance().build(ARouterUrlKt.PersonInfoUpdateUrl)
                        .navigation();
                break;
            case ServiceBean.ADDRESS:
                ARouter.getInstance().build(ARouterUrlKt.MyAddressUrl)
                        // .withString(ExtraCons.EXTRA_KEY_EDIT_MINE, MineAddressListFragment.MINE_ADDRESS_LIST_FRAGMENT)
                        .navigation();
                break;
            case ServiceBean.KEEPER:
                if (getApp().getUserInfo().getHkeeperId() < 0) {
                    ARouter.getInstance().build(ARouterUrlKt.MineKeeperContainerUrl).navigation();
                } else {
                    ARouter.getInstance().build(ARouterUrlKt.KeeperIndexUrl)
                            .navigation();
                }
                break;
            case ServiceBean.GM_ORDER_APPOINTMENT:
                ARouter.getInstance().build(ARouterUrlKt.OrderGMWorkingListUrl)
                        .withInt("type", 0)
                        .navigation();
                break;
            case ServiceBean.GM_ORDER_WORKING:
                ARouter.getInstance().build(ARouterUrlKt.OrderGMWorkingListUrl)
                        .withInt("type", 1)
                        .navigation();
                break;
            case ServiceBean.SETTINGS:
                ARouter.getInstance().build(MineInfoUrl)
                        .withString(ExtraCons.EXTRA_KEY_EDIT_MINE, SettingFragment.SETTING_FRAGMENT)
                        .navigation();
                break;
            case ServiceBean.OPINION:
                ARouter.getInstance().build(ARouterUrlKt.SysOpinionUrl)
                        .navigation();
                break;
            case ServiceBean.CSERVICE:
                showMessageOKCancel(getActivity(), String.format("拨打客服电话:%s", getString(R.string.service_phone)), v -> {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse(String.format("tel:%s", getString(R.string.service_phone))));
                    startActivity(intent);
                });
                break;
            case ServiceBean.REFUND:
                ARouter.getInstance().build(ARouterUrlKt.OrderRefundListUrl).navigation();
                break;

        }
    };

    @Subscribe
    public void onUserRefreshEvent(UpdateUserInfoEvent event) {
        if (event.getCode() == UpdateUserInfoEvent.RESP_OK) {
            initUI(getApp().getUserInfo());
        } else if (event.getCode() == UpdateUserInfoEvent.RESP_FAILED) {
            //  refreshLayout.finishRefresh(false);
        }
    }

    @Subscribe
    public void onAttentionEvent(DynamicAttentionEvent event) {
        tvAttentionNum.setText(String.valueOf(getApp().getUserInfo().getConcernNum()));
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        initUI(getApp().getUserInfo());
        initService();
        initSys();

    }

    private void initUI(UserResult result) {
        /// refreshLayout.finishRefresh(500);
        if (result == null) return;

        tvCommunity.setText(result.getLastCommunityName());
        Glide.with(this)
                .load(result.getHeadImg())
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(ivAvatar);

        tvUserName.setText(result.getNickName());
        tvUserDesc.setText(result.getSignature());
        tvFansNum.setText(String.valueOf(result.getFansNum()));
        tvLikeNum.setText(String.valueOf(result.getPraiseNum()));
        tvAttentionNum.setText(String.valueOf(result.getConcernNum()));

        ivUserVipFlag.setVisibility(result.isVip() ? View.VISIBLE : View.GONE);
        if (result.isVip() && !StringUtils.isEmpty(result.getPayMemberExpiredTime())) {
            tvInvalidDate.setText(String.format("会员到期至 %s", result.getVipInvalidTime()));
            tvVipAction.setText("立即续费");
        } else {
            tvInvalidDate.setText("家院里会员，省时 省心 省力 省钱");
            tvVipAction.setText("立即开通");
        }

        initProperty();
    }

    @Subscribe
    public void onHomeEvent(HomeEvent event) {
        if (event.getEvent() == HomeEvent.POST_ATTENTION) {
            int oldNum = getApp().getUserInfo().getConcernNum();
            getApp().getUserInfo().setConcernNum(++oldNum);
            tvAttentionNum.setText(String.valueOf(getApp().getUserInfo().getConcernNum()));
        } else if (event.getEvent() == HomeEvent.POST_ATTENTION_CANCEL) {
            int oldNum = getApp().getUserInfo().getConcernNum();
            if (oldNum > 0) {
                getApp().getUserInfo().setConcernNum(++oldNum);
            }
            tvAttentionNum.setText(String.valueOf(getApp().getUserInfo().getConcernNum()));
        }
    }

    private List<ServiceBean> getVipServiceItem() {
        List<ServiceBean> list = new ArrayList<>();
        list.add(new ServiceBean(R.mipmap.ic_person_vip_service_01, "社区服务", ServiceBean.VIP_SERVICE));
        list.add(new ServiceBean(R.mipmap.ic_person_vip_service_02, "上门服务", ServiceBean.VIP_SERVICE));
        list.add(new ServiceBean(R.mipmap.ic_person_vip_service_03, "维护服务", ServiceBean.VIP_SERVICE));
        list.add(new ServiceBean(R.mipmap.ic_person_vip_service_04, "定制服务", ServiceBean.VIP_SERVICE));
        list.add(new ServiceBean(R.mipmap.ic_person_vip_service_05, "免费上门", ServiceBean.VIP_SERVICE));
        list.add(new ServiceBean(R.mipmap.ic_person_vip_service_06, "专属管家", ServiceBean.VIP_SERVICE));
        return list;
    }

    private void initProperty() {
        List<ServiceBean> propertyList = new ArrayList<>();
        //FFF07E7F FFF59F7E  FFF8C26E  FF8398D4
        //propertyList.add(new PropertyBean("#FFF07E7F", "我的房屋", getApp().getUserInfo().getLastCommunityName()));
        // propertyList.add(new PropertyBean("#FFF59F7E", "房屋账单", "暂无"));
        //propertyList.add(new PropertyBean("#FFF8C26E", "我的车位", "未添加"));
        // propertyList.add(new PropertyBean("#FF8398D4", "我的车", "未添加"));
        propertyList.add(new ServiceBean(R.mipmap.ic_mine_house, "我的房屋", ServiceBean.HOUSE));
        propertyList.add(new ServiceBean(R.mipmap.ic_mine_house_order, "房屋账单", ServiceBean.HOUSE_ORDER));
        propertyList.add(new ServiceBean(R.mipmap.ic_mine_quan, "我的优惠券", ServiceBean.QUAN));
        propertyList.add(new ServiceBean(R.mipmap.ic_mine_committee, "业主委员会", ServiceBean.COMMITTEE));
        mPropertyAdapter.setList(propertyList);
    }

    private void initService() {
        List<ServiceBean> serviceList = new ArrayList<>();
        serviceList.add(new ServiceBean(R.mipmap.ic_mine_service_order, "我的订单", ServiceBean.ORDER));
        serviceList.add(new ServiceBean(R.mipmap.ic_mine_service_refund, "退款/售后", ServiceBean.REFUND));
        serviceList.add(new ServiceBean(R.mipmap.ic_mine_service_comments, "我的评价", ServiceBean.EVALUATE));
        serviceList.add(new ServiceBean(R.mipmap.ic_mine_service_active, "我的活动", ServiceBean.ACTIVE));
        serviceList.add(new ServiceBean(R.mipmap.ic_mine_service_circle, "我的圈子", ServiceBean.CIRCLE));
        // serviceList.add(new ServiceBean(R.mipmap.ic_mine_service_person, "个人信息", ServiceBean.PERSON_INFO));
        serviceList.add(new ServiceBean(R.mipmap.ic_mine_service_keeper, "我的管家", ServiceBean.KEEPER));

        serviceList.add(new ServiceBean(R.mipmap.ic_mine_service_gm_appointment, "装修预约", ServiceBean.GM_ORDER_APPOINTMENT));
        serviceList.add(new ServiceBean(R.mipmap.ic_mine_service_gm_working, "直播装修", ServiceBean.GM_ORDER_WORKING));
        mServiceAdapter.setList(serviceList);
    }

    private void initSys() {
        List<ServiceBean> sysList = new ArrayList<>();
        sysList.add(new ServiceBean(R.mipmap.ic_mine_service_address, "收货地址", ServiceBean.ADDRESS));
        sysList.add(new ServiceBean(R.mipmap.ic_mine_sys_settings, "我的设置", ServiceBean.SETTINGS));
        sysList.add(new ServiceBean(R.mipmap.ic_mine_service_opinion, "意见反馈", ServiceBean.OPINION));
        sysList.add(new ServiceBean(R.mipmap.ic_mine_service_cservice, "客服热线", ServiceBean.CSERVICE));
        mSysAdapter.setList(sysList);
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == PICK_COMMUNITY) {
            if (RESULT_OK == resultCode) {
                if (data != null) {
                    CommunityResult result = (CommunityResult) data.getSerializable("data");
                    updateCommunity(result);
                }
            }
        }
    }

    private void updateCommunity(CommunityResult community) {
        if (community == null) return;
        getAppComponent().repositoryManager().obtainRetrofitService(CommunityService.class)
                .updateCommunity(community.getId())
                .doOnSubscribe(act -> showLoading("正在同步..."))
                .doFinally(this::hideLoading)
                .compose(RxUtils.schedulerHelper())
                .compose(RxUtils.handleCode())
                .subscribe(new ApiCallBack<Integer>() {
                    @Override
                    public void onSuccess(@NonNull Integer result) {
                        showMessage("操作成功");
                        tvCommunity.setText(community.getCommunityName());
                        EventBus.getDefault().post(new UpdateUserInfoEvent(UpdateUserInfoEvent.REQUEST));
                        AccountStore.updateCommunity(community.getId(), community.getCommunityName());
                        EventBus.getDefault().post(new GlobalEvent(GlobalEvent.REFRESH));
                        ServiceHistoryStore.clear();
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        subscribe(d);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        showMessage("操作失败");
                    }
                });
    }
}
